package filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        HttpSession session = req.getSession();
        
        // 设置session超时时间为30分钟
        session.setMaxInactiveInterval(30 * 60);
        
        // 获取当前请求的URI
        String uri = req.getRequestURI();
        
        // 这些路径不需要过滤
        if (uri.contains("/login.jsp") || uri.contains("/register.jsp") 
            || uri.contains("/css/") || uri.contains("/js/") 
            || uri.contains("/images/") || uri.contains("/LoginServlet")
            || uri.contains("/RegisterServlet")) {
            chain.doFilter(request, response);
            return;
        }

        // 检查用户是否已登录
        Object user = session.getAttribute("user");
        if (user == null) {
            // 未登录，重定向到登录页面
            resp.sendRedirect(req.getContextPath() + "/login.jsp");
        } else {
            // 已登录，继续请求
            chain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {
    }
} 